package com.ruoyi.learn.java.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalMemoryLeakDemo {

    // 非静态的ThreadLocal（更易发生泄漏）
    private ThreadLocal<byte[]> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalMemoryLeakDemo demo = new ThreadLocalMemoryLeakDemo();
        demo.leakDemo();
    }

    public void leakDemo() throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 模拟线程池重复使用线程
        for (int i = 0; i < 10000; i++) {
            executor.execute(() -> {
                // 每个任务设置一个1MB的大对象
                try {
                    threadLocal.set(new byte[1024 * 1024*1024]); // 1MB

                }finally {
                    // 关键：确保remove()被调用
//                    threadLocal.remove();
                }

                // 模拟业务逻辑
                System.out.println(Thread.currentThread().getName() + " 使用了ThreadLocal");

                // 故意不调用remove() → 内存泄漏
                // threadLocal.remove();
            });
            Thread.sleep(100); // 给GC一点时间
        }

        executor.shutdown();
        System.out.println("演示结束，观察内存情况");
    }
}